package com.fantasy.httpclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * HttpGet 创建时转义参数
 * */
public class HttpGetTest {

	public static void main(String[] args) throws ParseException, IOException {
		HttpClient httpclient = HttpClients.createDefault();
		HttpGet httpGet;
		String url = "https://www.baidu.com?params={\"a\"=\"aaa\"}";
		url = encodeUrlData(url);
		System.out.println("转义后 的连接" + url );
		httpGet = new HttpGet(url);
		HttpResponse response = httpclient.execute(httpGet);
		HttpEntity entity = response.getEntity();
		//System.out.println(response.getStatusLine().getStatusCode());
		if(response.getStatusLine().getStatusCode() == 404){
			System.out.println("  页面不存在404");
		}
		String respContent = EntityUtils.toString(entity , "utf-8").trim();
		System.out.println( respContent);
		
	}
	
	/**
	 * 带参数时转义
	 * */
	private static String encodeUrlData(String url) throws UnsupportedEncodingException{
		if(null == url){
			return url;
		}
		int inx = url.indexOf("?");
		if(inx == -1){
			return "";
		}
		String data = url.substring(inx + 1, url.length());
		System.out.println("转义数据：" + data);
		data = URLEncoder.encode(data, "UTF-8");
		url = url.substring(0,inx + 1) + data;
		return url;
	}
}
